package com.example.demo.udp;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class UDPServerHandler extends SimpleChannelInboundHandler<DatagramPacket> implements ChannelHandler {
    private static UDPServerHandler udpServerHandler;
    private UDPService udpService;

    @Autowired
    public void setUdpService(UDPService udpService) {
        this.udpService = udpService;
    }

    @PostConstruct
    public void init() {
        udpServerHandler = this;
    }

    //处理接收到的数据
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket) throws Exception {
        //String body = new String(req, "UTF-8");
        //System.out.println(body);//打印收到的信息
        udpServerHandler.udpService.handleReceivedPackage(datagramPacket);

        /*//向客户端发送消息
        String json = "I receive your message";
        // 由于数据报的数据是以字符数组传的形式存储的，所以传转数据
        byte[] bytes = json.getBytes("UTF-8");
        DatagramPacket data = new DatagramPacket(Unpooled.copiedBuffer(bytes), datagramPacket.sender());
        channelHandlerContext.writeAndFlush(data);//向客户端发送消息*/
    }

    //读取完成后处理方法
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        //System.out.println("EchoServerHandler.channelReadComplete");
        ctx.flush();
    }

    //处理异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 当出现异常就关闭连接
        cause.printStackTrace();
        //ctx.close();
    }
}
